/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as _ from "lodash"
import * as React from "react"
import { CSSProperties, MouseEventHandler } from "react"
import Icon from "../../icon"
import { prefixClassName } from "../style"

import "./index.scss"

interface InputNumberProps {
  max?: number;
  min?: number;
  value: number;
  style?: CSSProperties;
  onChange?: (value: number) => void;
  onClick?: MouseEventHandler<HTMLDivElement>;
}

export default function InputNumber(props: InputNumberProps) {
  const { max = Number.MAX_VALUE, min = Number.MIN_VALUE, value, onChange, ...restProps } = props

  function setValue(newValue: number) {
    if (min && max && _.isFunction(onChange)) {
      const minmaxNewValue = Math.min(Math.max(min, newValue), max)
      if (minmaxNewValue !== value) {
        onChange(minmaxNewValue)
      }
    }
  }

  return (
    <div className={prefixClassName("input-number")} {...restProps}>
      <Icon type="move" size="xxs" onClick={() => setValue(value - 1)}/>
      <input type="number" style={{ height: "100%" }} min={min} max={max}
             value={value.toString()}
             onChange={e => setValue(_.toNumber(e.target.value))}/>
      <Icon type="add" size="xxs" onClick={() => setValue(value + 1)}/>
    </div>
  )
}
